<template>
  <div class="main-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="sidebarWidth" class="sidebar">
        <div class="sidebar-header">
          <div class="logo">
            <div class="logo-placeholder">🎓</div>
            <h1 v-show="!appStore.sidebarCollapsed" class="title">鸥鹏面试官</h1>
          </div>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="appStore.sidebarCollapsed"
          :unique-opened="true"
          router
          class="sidebar-menu"
        >
          <template v-for="item in menuList" :key="item.id">
            <el-sub-menu
              v-if="item.children && item.children.length > 0"
              :index="item.id"
            >
              <template #title>
                <el-icon v-if="item.icon">
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.title }}</span>
              </template>
              
              <el-menu-item
                v-for="child in item.children"
                :key="child.id"
                :index="child.path"
              >
                <el-icon v-if="child.icon">
                  <component :is="child.icon" />
                </el-icon>
                <span>{{ child.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <el-menu-item v-else :index="item.path">
              <el-icon v-if="item.icon">
                <component :is="item.icon" />
              </el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      
      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <el-button
              type="text"
              size="large"
              @click="appStore.toggleSidebar"
            >
              <el-icon>
                <Fold v-if="!appStore.sidebarCollapsed" />
                <Expand v-else />
              </el-icon>
            </el-button>
            
            <el-breadcrumb separator="/">
              <el-breadcrumb-item
                v-for="item in breadcrumbList"
                :key="item.path"
                :to="item.path"
              >
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <div class="header-right">
            <!-- 通知 -->
            <NotificationDropdown ref="notificationRef" />

            <!-- 主题切换 -->
            <ThemeToggle />

            <!-- 用户菜单 -->
            <el-dropdown @command="handleUserCommand">
              <div class="user-info">
                <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                  {{ userStore.userName.charAt(0) }}
                </el-avatar>
                <span class="username">{{ userStore.userName }}</span>
                <el-icon><ArrowDown /></el-icon>
              </div>
              
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon><Setting /></el-icon>
                    系统设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 主内容 -->
        <el-main class="main-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import ThemeToggle from '@/components/ThemeToggle.vue'
import NotificationDropdown from '@/components/NotificationDropdown.vue'
import type { MenuItem } from '@/types'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

// 通知组件引用
const notificationRef = ref()

// 侧边栏宽度
const sidebarWidth = computed(() => {
  return appStore.sidebarCollapsed ? '64px' : '240px'
})

// 当前激活的菜单
const activeMenu = computed(() => {
  return route.path
})

// 面包屑导航
const breadcrumbList = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    title: item.meta.title as string,
    path: item.path
  }))
})

// 菜单列表
const menuList = computed<MenuItem[]>(() => {
  const userRole = userStore.userInfo?.role
  
  const allMenus: MenuItem[] = [
    {
      id: 'dashboard',
      title: '仪表盘',
      icon: 'Dashboard',
      path: '/dashboard'
    },
    {
      id: 'students',
      title: '学生管理',
      icon: 'User',
      roles: ['admin', 'teacher'],
      children: [
        { id: 'student-list', title: '学生列表', path: '/students/list' },
        { id: 'student-statistics', title: '学生统计', path: '/students/statistics' }
      ]
    },
    {
      id: 'resume',
      title: '简历管理',
      icon: 'Document',
      children: userRole === 'student' ? [
        { id: 'my-resume', title: '我的简历', path: '/resume/my' }
      ] : [
        { id: 'resume-review', title: '简历审核', path: '/resume/review' },
        { id: 'reviewed-resume', title: '已审批简历', path: '/resume/reviewed' }
      ]
    },
    {
      id: 'interviews',
      title: '面试管理',
      icon: 'ChatDotRound',
      children: userRole === 'student' ? [
        { id: 'interview-my', title: '面试列表', path: '/interviews/my' },
        { id: 'interview-practice', title: '面试练习', path: '/interviews/practice' }
      ] : [
        { id: 'interview-applications', title: '面试列表', path: '/interviews/applications' },
        { id: 'interview-schedule', title: '安排面试', path: '/interviews/schedule' },
        { id: 'interview-questions', title: '题库管理', path: '/interviews/questions' }
      ]
    },
    {
      id: 'jobs',
      title: '岗位管理',
      icon: 'Briefcase',
      children: userRole === 'student' ? [
        { id: 'job-list', title: '岗位列表', path: '/jobs/list' },
        { id: 'my-applications', title: '我的申请', path: '/jobs/my-applications' }
      ] : [
        { id: 'job-list', title: '岗位列表', path: '/jobs/list' },
        { id: 'job-create', title: '发布岗位', path: '/jobs/create' },
        { id: 'job-applications', title: '申请管理', path: '/jobs/applications' },
        { id: 'companies', title: '公司管理', path: '/jobs/companies' },
        { id: 'job-statistics', title: '岗位统计', path: '/jobs/statistics' }
      ]
    },
    {
      id: 'notifications',
      title: '通知中心',
      icon: 'Bell',
      path: '/notifications'
    },
    {
      id: 'files',
      title: '文件管理',
      icon: 'Folder',
      path: '/files',
      roles: ['admin', 'teacher']
    },
    {
      id: 'system',
      title: '系统管理',
      icon: 'Setting',
      roles: ['admin'],
      children: [
        { id: 'system-users', title: '用户管理', path: '/system/users' },
        { id: 'system-roles', title: '角色权限', path: '/system/roles' },
        { id: 'system-schools', title: '校区管理', path: '/system/schools' },
        { id: 'system-majors', title: '专业管理', path: '/system/majors' },
        { id: 'system-grades', title: '年级管理', path: '/system/grades' },
        { id: 'system-logs', title: '系统日志', path: '/system/logs' },
        { id: 'system-settings', title: '系统设置', path: '/system/settings' }
      ]
    }
  ]
  
  // 根据用户角色过滤菜单
  return allMenus.filter(menu => {
    if (menu.roles && userRole) {
      return menu.roles.includes(userRole)
    }
    return true
  })
})

// 处理用户菜单命令
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      if (userStore.isAdmin) {
        router.push('/system/settings')
      } else {
        ElMessage.info('没有权限访问系统设置')
      }
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await userStore.logout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        // 用户取消
      }
      break
  }
}

onMounted(() => {
  // 初始化应用设置
  appStore.initApp()
})
</script>

<style lang="scss" scoped>
.main-layout {
  height: 100vh;
  
  .el-container {
    height: 100%;
  }
}

.sidebar {
  background: var(--sidebar-bg);
  border-right: 1px solid var(--sidebar-border);
  transition: all 0.3s ease;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);

  .sidebar-header {
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid var(--sidebar-border);
    background: var(--sidebar-bg);

    .logo {
      display: flex;
      align-items: center;
      color: var(--sidebar-text-active);
      transition: color 0.3s ease;

      .logo-placeholder {
        width: 32px;
        height: 32px;
        margin-right: 8px;
        font-size: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--sidebar-text-active);
        transition: color 0.3s ease;
      }

      .title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        white-space: nowrap;
        color: var(--sidebar-text-active);
        transition: color 0.3s ease;
      }
    }
  }
  
  .sidebar-menu {
    border: none;
    background: var(--sidebar-bg);

    // 菜单项基础样式
    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      color: var(--sidebar-text);
      background-color: var(--sidebar-item-bg);
      border-radius: 6px;
      margin: 4px 8px;
      transition: all 0.3s ease;

      &:hover {
        color: var(--sidebar-text-hover);
        background-color: var(--sidebar-item-bg-hover);
      }

      .el-icon {
        color: inherit;
        transition: color 0.3s ease;
      }
    }

    // 激活状态的菜单项
    :deep(.el-menu-item.is-active) {
      color: var(--sidebar-text-active);
      background-color: var(--sidebar-item-bg-active);
      border-left: 3px solid var(--sidebar-item-border-active);
      font-weight: 600;

      .el-icon {
        color: var(--sidebar-text-active);
      }
    }

    // 子菜单样式
    :deep(.el-sub-menu) {
      .el-sub-menu__title {
        &:hover {
          background-color: var(--sidebar-item-bg-hover);
        }
      }

      &.is-active > .el-sub-menu__title {
        color: var(--sidebar-text-active);
        background-color: var(--sidebar-item-bg-hover);
      }

      .el-menu {
        background-color: var(--sidebar-submenu-bg);

        .el-menu-item {
          color: var(--sidebar-submenu-text);
          padding-left: 50px !important;

          &:hover {
            color: var(--sidebar-text-hover);
            background-color: var(--sidebar-item-bg-hover);
          }

          &.is-active {
            color: var(--sidebar-text-active);
            background-color: var(--sidebar-item-bg-active);
            border-left: 3px solid var(--sidebar-item-border-active);
          }
        }
      }
    }

    // 折叠状态下的样式
    &.el-menu--collapse {
      :deep(.el-menu-item),
      :deep(.el-sub-menu__title) {
        text-align: center;
        padding: 0 20px;

        .el-icon {
          margin-right: 0;
        }
      }
    }
  }
}

.header {
  background: var(--header-bg);
  border-bottom: 1px solid var(--header-border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  .header-left {
    display: flex;
    align-items: center;

    .el-button {
      color: var(--text-color-primary);
      transition: all 0.3s ease;

      &:hover {
        color: var(--color-primary);
        background-color: var(--fill-color-light);
      }
    }

    .el-breadcrumb {
      margin-left: 16px;

      :deep(.el-breadcrumb__item) {
        .el-breadcrumb__inner {
          color: var(--text-color-secondary);
          transition: color 0.3s ease;

          &:hover {
            color: var(--color-primary);
          }
        }

        &:last-child .el-breadcrumb__inner {
          color: var(--text-color-primary);
          font-weight: 500;
        }
      }

      :deep(.el-breadcrumb__separator) {
        color: var(--text-color-placeholder);
      }
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background-color: var(--fill-color-light);
      }

      .username {
        font-size: 14px;
        color: var(--text-color-primary);
        font-weight: 500;
      }

      .el-avatar {
        border: 2px solid var(--border-color-lighter);
        transition: border-color 0.3s ease;

        &:hover {
          border-color: var(--color-primary);
        }
      }
    }
  }
}

.main-content {
  background: var(--bg-color-page);
  padding: 20px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    height: 100vh;
  }
  
  .header {
    .header-left {
      .el-breadcrumb {
        display: none;
      }
    }
    
    .header-right {
      .user-info {
        .username {
          display: none;
        }
      }
    }
  }
}
</style>
